﻿using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using CNative.WebApi.Common;
using Autofac;
using System.Reflection;
using Autofac.Integration.WebApi;
using CNative.WebApi.Utils;

namespace CNative.WebApiHost
{
    class Startup
    {
        public void Configuration(IAppBuilder appBuilder)
        {
            HttpConfiguration config = new HttpConfiguration();

            ConfigureIoC(appBuilder, config);

            WebApiConfig.Register(config);
            //config.MapHttpAttributeRoutes();

            //config.Routes.MapHttpRoute(
            //    name: "DefaultApi",
            //    routeTemplate: "api/{controller}/{id}",
            //    defaults: new { id = RouteParameter.Optional }
            //);

            config.Filters.Add(new MyExceptionFilter());
            //config.Filters.Add(new MyActionFilter());

            SwaggerConfig.Register(config);

            appBuilder.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            appBuilder.UseWebApi(config);
        }

        private void ConfigureIoC(IAppBuilder app, HttpConfiguration config)
        {
            var builder = new ContainerBuilder();

            var controllerAssemblies = AssemblyHelper.GetAssemblies("Controllers");
            if (controllerAssemblies == null) controllerAssemblies = new List<Assembly>();
            controllerAssemblies.Add(Assembly.GetExecutingAssembly());

            builder.RegisterApiControllers(controllerAssemblies.ToArray()).InstancePerRequest();

            builder.RegisterWebApiFilterProvider(config);

            //register type specific shit here
           //RegisterRequestTypes(builder);

            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(config);
            app.UseWebApi(config);
        }
        //private void RegisterRequestTypes(ContainerBuilder builder)
        //{
        //    builder.RegisterType<Library>().As<ILibrary>();
        //}
    }
}
